package cn.uyunsky.platform.servlet;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.uyunsky.platform.util.PL;

public class ServletUtil {

	private static String encoding = "UTF-8";

	public static Map getSessionData(HttpServletRequest request) {
		Map contextData = new HashMap();

		HttpSession session = request.getSession();
		Enumeration sessionEmnu = session.getAttributeNames();
		while (sessionEmnu.hasMoreElements()) {
			String name = (String) sessionEmnu.nextElement();
			contextData.put(name, session.getAttribute(name));
		}
		return contextData;
	}

	/**
	 * <p>Description: 将对象转换为JSON字符串输出</p>
	 * 参数说明:
	 * @param obj 返回JSON对象
	 * @param response
	 */
	public static void wirteJSONObj(Object obj, HttpServletResponse response) {
		writeJSONString(PL.JSON.toJSON(obj), response);
	}

	/**
	 * <p>Description: 将字符串直接返回,此字符串必须是合法的JSON字符串</p>
	 * 参数说明:
	 * @param str 合法的JSON字符串
	 * @param response 
	 */
	public static void writeJSONString(String str, HttpServletResponse response) {
		try {
			writeJSONByte(str.getBytes(encoding), response);
		} catch (UnsupportedEncodingException e) {
			try {
				response.getOutputStream().write("{success:false,msg:'返回数据失败'}".getBytes(encoding));
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
	}

	/**
	 * <p>Description: 将字符串byte数组直接返回</p>
	 * 参数说明:
	 * @param buff 合法的json字符串byte数组
	 * @param response 
	 */
	private static void writeJSONByte(byte[] buff, HttpServletResponse response) {
		//response.setCharacterEncoding(encoding);
		response.setContentType("text/html; charset=UTF-8");
		try {
			response.getOutputStream().write(buff);
		} catch (IOException e) {
			// 有可能是JSON.toJSONBytes失败,这里处理一下
			try {
				response.getOutputStream().write("{success:false,msg:'返回数据失败'}".getBytes(encoding));
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
	}

}
